package summer.codegenerator.web.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import summer.codegenerator.Constant;
import summer.codegenerator.common.util.CookieUtil;
import summer.codegenerator.dto.ResultFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class TokenInterceptor implements HandlerInterceptor {

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Boolean goon = false;
        // TOKEN校验
        Cookie tokenCookie = CookieUtil.getCookieByName(request, Constant.TOKEN_KEY);
        if (tokenCookie != null && StringUtils.isNotBlank(tokenCookie.toString())) {
            // 后期添加校验
            goon = true;
        }
        if (!goon) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.append(ResultFactory.OFFLINE);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
        return goon;
    }
}